package server

import (
	"shop-api/consts"
	"shop-api/internal/model"
)

type GoodTypeRes struct {
	ID       uint           `json:"id"`
	Name     string         `json:"name"`
	Icon     string         `json:"icon"`
	Children []*GoodTypeRes `json:"children"`
}

func GetGoodType(position uint) ([]*GoodTypeRes, error) {
	var infos []*model.GoodType
	var err error
	var res []*GoodTypeRes

	goodTypeMod := new(model.GoodType)
	switch position {
	case consts.GoodTypePositionHomeHeader:
		fallthrough
	case consts.GoodTypePositionHomeCenter:
		infos, err = goodTypeMod.GetAllByPosition(position)
		if err != nil {
			return nil, err
		}
		for _, val := range infos {
			res = append(res, &GoodTypeRes{
				ID:   val.ID,
				Name: val.Name,
				Icon: val.Icon,
			})
		}
		return res, nil
	default:
		infos, err = goodTypeMod.GetAll()
		if err != nil {
			return nil, err
		}

		lv2Map := make(map[uint][]*GoodTypeRes)
		lv3Map := make(map[uint][]*GoodTypeRes)
		for _, val := range infos {
			resVal := &GoodTypeRes{
				ID:   val.ID,
				Name: val.Name,
				Icon: val.Icon,
			}
			if val.Lv == consts.GoodTypeLv2 {
				lv2Map[val.PID] = append(lv2Map[val.PID], resVal)
			}
			if val.Lv == consts.GoodTypeLv3 {
				lv3Map[val.PID] = append(lv3Map[val.PID], resVal)
			}
		}

		for _, val := range lv2Map {
			for _, val1 := range val {
				lv3Infos, ok := lv3Map[val1.ID]
				if !ok {
					continue
				}

				val1.Children = lv3Infos
			}
		}

		for _, val := range infos {
			if val.Lv == consts.GoodTypeLv1 {
				lv2Infos, ok := lv2Map[val.ID]
				if !ok {
					continue
				}
				res = append(res, &GoodTypeRes{
					ID:       val.ID,
					Name:     val.Name,
					Icon:     val.Icon,
					Children: lv2Infos,
				})
			}
		}
	}
	return res, nil
}
